package com.bid.base.common.util;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
/**
 * <strong>Description : </strong> <br>
 * <p>
 * <strong>北京正源德标科技信息有限责任公司</strong> <br>
 * </p>
 * <br>
 *
 * @author : zhaots
 * @date Date : 2020年12月08日 17:18
 * 修改人 修改日期 修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Data
@Slf4j
public class ReverseEngine {


    private   String DATA_URL = "";
    private   String USERNAME = "";
    private   String PASSWORD = "";
    private String[] tableNames = new String[] {};

    private   String OutputDir = "C:\\Users\\Administrator\\Desktop\\Test";
    private String packageName = "com.bid.xxx";


    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";

    /**
     * false为不通过
     * @return
     */
    private boolean checkParamValid() {
        String[] split = packageName.split("\\.");
        if(!(split.length>2)){
            log.error("包名长度 {}，不能小于三级，比如com.bid.test  ",split.length);
            return false;
        }

        File file = new File(getOutputDir());
        if(!file.exists()){
            file.mkdirs();
        }

        return true;
    }

    private ReverseEngine(){}

    /**
     *
     * @param dataUrl  比如 "jdbc:mysql://47.xx.229.xx:3306/zydb?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull";
     * @param username 用户名
     * @param password 密码
     */
    public ReverseEngine(String dataUrl, String username, String password,String[] tableNames){
        this.DATA_URL = dataUrl;
        this.USERNAME = username;
        this.PASSWORD = password;
        this.tableNames = tableNames;
    }

    public void generate(){
        if (!checkParamValid()){
            return;
        }
        log.info("逆向工程开始生成");
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setDriverName(DRIVER);
        dsc.setUrl(DATA_URL);
        dsc.setUsername(USERNAME);
        dsc.setPassword(PASSWORD);
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(OutputDir);
        gc.setFileOverride(true);
        gc.setActiveRecord(true);
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML columList
        gc.setAuthor(" author");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        gc.setSwagger2(true);
        StrategyConfig strategy = new StrategyConfig();
//strategy.setTablePrefix(new String[] { "SYS_" });// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setInclude(tableNames); // 需要生成的表
        strategy.setEntityLombokModel(true);
        PackageConfig pc = new PackageConfig();
        pc.setParent(packageName);
        pc.setController("controller");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setEntity("entity");
        pc.setMapper("dao");
//        pc.setXml("xml");
        AutoGenerator mpg = new AutoGenerator();
        mpg.setDataSource(dsc);         //数据源配置
        mpg.setGlobalConfig(gc);        //全局配置
        mpg.setStrategy(strategy);      //生成策略配置
        mpg.setPackageInfo(pc);         //包配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");
//                map.put("swagger2",true);
                this.setMap(map);
            }
        };
        //xml生成路径
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return "src/main/resources/"+"/mybatis/tables/"+tableInfo.getEntityName()+"Mapper.xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // 关闭默认 xml 生成，调整生成 至 根目录
        TemplateConfig tc = new TemplateConfig();
        //        tc.setXml(null);
        mpg.setCfg(cfg);                //xml配置
        mpg.setTemplate(tc);            //
        // 执行生成
        mpg.execute();
        log.info("完成,生成的路径是：{}",getOutputDir());
    }




    public static void main(String[] args) {
         final String DRIVER = "com.mysql.cj.jdbc.Driver";
         final String DATA_URL = "jdbc:mysql://172.20.20.6:3306/zydb_dev?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull";
         final String USERNAME = "root";
         final String PASSWORD = "abc123";
        String[] tableNames = new String[]{"B_ELEC_EXPERT"};

        ReverseEngine engine = new ReverseEngine(DATA_URL, USERNAME, PASSWORD, tableNames);
        engine.setPackageName("com.bid.base.server");
        engine.generate();
    }
}
